<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    table {
      width: 800px;
      margin: 20px auto;
    }
  </style>
</head>

<body>
  <h1>用户列表页面</h1>
  <table border="1">
    <thead>
      <tr>
        <th>id</th>
        <th>用户名</th>
        <th>手机号</th>
        <th>邮箱</th>
        <th>Vip</th>
        <th>是否冻结</th>
        <th>创建日期</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody id="mytbody">
      <!-- <tr>
        <td>id</td>
        <td>id</td>
        <td>id</td>
        <td>id</td>
        <td>id</td>
        <td>id</td>
        <td>id</td>
        <td>
          <button class="del">删除</button>
        </td>
      </tr> -->
    </tbody>
  </table>
  <script src="./javascripts/jquery-3.4.1.min.js"></script>
  <script>
    // 调用用户列表接口
    function loadList() {
      $.ajax({
        url: "http://127.0.0.1:3000/users/userlist",
        type: "post",
        dataType: "json",
        data: {},
        success: function (res) {
          console.log(res)
          var str = ""
          $.each(res, function (index, ele) {
            str += `
            <tr>
                <td>${ele._id}</td>
                <td>${ele.username}</td>
                <td>${ele.phone}</td>
                <td>${ele.email}</td>
                <td>${ele.vip ? "会员" : "非会员"}</td>
                <td>${ele.isfreeze ? "冻结" : "可用"}</td>
                <td>${new Date(ele.createAt).toLocaleString()}</td>
                <td>
                  <button class="del" onclick="del('${ele.username}')">删除</button>  
                  <button class="del" onclick="updateVip('${ele._id}','${ele.vip}')">${ele.vip ? "退出会员" : "充值会员"}</button>
                </td>
              </tr>`
          })
          $("#mytbody").html(str)
        }
      })
    }
    loadList()

    // 删除方法
    function del(username) {
      $.ajax({
        url: "http://127.0.0.1:3000/users/del",
        type: "post",
        dataType: "json",
        data: {
          username: username
        },
        success: function (res) {
          if (res.success) {
            loadList()//删除后加载列表
          }
        }
      })
    }
    // 修改vip
    function updateVip(_id, vip) {
      console.log(_id, vip)
      var vipdata = vip == "0" ? 1 : 0;
      $.ajax({
        url: "http://127.0.0.1:3000/users/vip",
        type: "post",
        dataType: "json",
        data: {
          _id: _id,
          vip: vipdata
        },
        success: function (res) {
          console.log(res)
          loadList();
        }
      })
    }

  </script>
</body>

</html>